package net.mayee.alice.web.controller.base;

import net.mayee.alice.common.Definiens;
import net.mayee.alice.service.admin.account.LanguageService;
import net.mayee.alice.service.admin.account.RoleService;
import net.mayee.alice.service.admin.account.UserService;
import net.mayee.common.AliceHelper;
import net.mayee.common.CoderHelper;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;
import org.springframework.web.servlet.i18n.SessionLocaleResolver;
import org.springframework.web.servlet.support.RequestContext;

import javax.servlet.http.HttpServletRequest;
import java.util.*;
import java.util.regex.Pattern;

public class BaseController {

    public static final Pattern EMAIL_PATTERN = Pattern
            .compile("^[a-zA-Z0-9.!#$%&'*+\\/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$");
    public static final Pattern MOBILE_PHONE_NUMBER_PATTERN = Pattern
            .compile("^0{0,1}(13[0-9]|15[0-9]|14[0-9]|18[0-9])[0-9]{8}$");
    public static final Pattern LOGIN_NAME_PATTERN = Pattern
            .compile("^([a-zA-Z0-9]{4,20})$");
    public static final Pattern LOGIN_PASSWORD_PATTERN = Pattern
            .compile("^([a-zA-Z0-9_]{4,16})$");


    @Autowired
    private HttpServletRequest request;

    @Autowired
    private UserService userService;
    @Autowired
    private RoleService roleService;
    @Autowired
    private LanguageService languageService;

    public RoleService getRoleService() {
        return roleService;
    }

    public LanguageService getLanguageService() {
        return languageService;
    }

    public UserService getUserService() {
        return userService;
    }

    protected final String getRealPath(HttpServletRequest request) {
        return request.getSession().getServletContext().getRealPath("/");
    }

    protected final String getMessage(String key, String[] values, Locale locale) {
        ApplicationContext ac = WebApplicationContextUtils
                .getRequiredWebApplicationContext(request.getSession()
                        .getServletContext());
        if (locale == null) {
            locale = getSessionLocale();
        }
        return ac.getMessage(key, values, "Key Null", locale);
    }

    protected final String getMessage(String key) {
        return new RequestContext(request).getMessage(key);
    }

    protected final String getMessage(String key, String defaultMessage) {
        return new RequestContext(request).getMessage(key, defaultMessage);
    }

    protected final String getMessage(String key, String[] values, String defaultMessage) {
        return new RequestContext(request).getMessage(key, values, defaultMessage);
    }

    protected final String getMessage(String key, String[] values) {
        return new RequestContext(request).getMessage(key, values);
    }

    protected final Locale getSessionLocale() {
        return (Locale) request.getSession().getAttribute(
                SessionLocaleResolver.LOCALE_SESSION_ATTRIBUTE_NAME);
    }

    protected final void setSessionLocale(Locale locale) {
        request.getSession().setAttribute(
                SessionLocaleResolver.LOCALE_SESSION_ATTRIBUTE_NAME, locale);
    }

    protected final void setDefaultSessionLocale() {
        if (request.getSession().getAttribute(SessionLocaleResolver.LOCALE_SESSION_ATTRIBUTE_NAME) == null) {
            String default_code = AliceHelper.getInstance().getJoddProps().getValue("system.default.language");
            setSessionLocale(new Locale(default_code.split("_")[0], default_code.split("_")[1]));
        }
    }

    protected final void setSessionLocale(String code) {
        request.getSession().setAttribute(
                SessionLocaleResolver.LOCALE_SESSION_ATTRIBUTE_NAME,
                new Locale(code.split("_")[0], code.split("_")[1]));
    }

    protected HttpServletRequest getRequest() {
        return request;
    }

    protected String getPath() {
        return request.getContextPath();
    }

    protected String getBasePath() {
        return request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + getPath() + "/";
    }

    protected String getAjaxRegisterJSONString(List<String> errorMsgList, HashMap<String, String> map) throws JSONException {
        JSONObject result = doAjaxJSONObject(errorMsgList, Definiens.ERR_SYS_10);
        Set<String> keySet = map.keySet();
        for (String key : keySet) {
            result.put(key, map.get(key));
        }
        return result.toString();
    }

    protected String getAjaxRegisterJSONString(List<String> errorMsgList, String msg) throws JSONException {
        JSONObject result = doAjaxJSONObject(errorMsgList, Definiens.ERR_SYS_10);
        result.put(Definiens.MSG_DESC, msg);
        return result.toString();
    }

    protected String getAjaxRegisterJSONString(List<String> errorMsgList) throws JSONException {
        return doAjaxJSONObject(errorMsgList, Definiens.ERR_SYS_10).toString();
    }

    protected String getAjaxUpdateJSONString(List<String> errorMsgList, String msg) throws JSONException {
        JSONObject result = doAjaxJSONObject(errorMsgList, Definiens.ERR_SYS_11);
        result.put(Definiens.MSG_DESC, msg);
        return result.toString();
    }

    protected String getAjaxUpdateJSONString(List<String> errorMsgList, HashMap<String, String> map) throws JSONException {
        JSONObject result = doAjaxJSONObject(errorMsgList, Definiens.ERR_SYS_11);
        Set<String> keySet = map.keySet();
        for (String key : keySet) {
            result.put(key, map.get(key));
        }
        return result.toString();
    }

    /**
     * 用于验证码的ajax调用返回
     *
     * @param errorMsgList 错误信息列表
     * @param map          存放其它要返回值的map
     * @return
     * @throws JSONException
     */
    protected String getAjaxValidateJSONString(List<String> errorMsgList, Map<String, String> map) throws JSONException {
        JSONObject result = doAjaxJSONObject(errorMsgList, Definiens.ERR_SYS_13);
        Set<String> keySet = map.keySet();
        for (String key : keySet) {
            result.put(key, map.get(key));
        }
        return result.toString();
    }

    protected String getAjaxUpdateJSONString(List<String> errorMsgList) throws JSONException {
        return doAjaxJSONObject(errorMsgList, Definiens.ERR_SYS_11).toString();
    }

    protected String getAjaxDeleteJSONString(List<String> errorMsgList) throws JSONException {
        return doAjaxJSONObject(errorMsgList, Definiens.ERR_SYS_12).toString();
    }

    protected String getAjaxValidateJSONString(List<String> errorMsgList) throws JSONException {
        return doAjaxJSONObject(errorMsgList, Definiens.ERR_SYS_13).toString();
    }

    private JSONObject doAjaxJSONObject(List<String> errorMsgList, String code) throws JSONException {
        JSONObject result = new JSONObject();
        JSONArray array = new JSONArray();
        if (errorMsgList != null && errorMsgList.size() > 0) {
            result.put(Definiens.MSG_ID, code);
            result.put(Definiens.MSG_DESC,
                    this.getMessage(CoderHelper.getInstance().getTextBySystemCode(code)));
            for (String msg : errorMsgList) {
                JSONArray ja = new JSONArray();
                ja.put(msg);
                array.put(ja);
            }
        } else {
            result.put(Definiens.MSG_ID, Definiens.SUCCESS_DEFAULT);
            result.put(Definiens.MSG_DESC,
                    this.getMessage(
                            CoderHelper.getInstance().getTextBySystemCode(Definiens.SUCCESS_DEFAULT)));
        }
        result.put(Definiens.MSG_ERRORS, array);
        return result;
    }

}
